package com.sahyadri.web.util.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import com.sahyadri.web.util.service.adpater.UserDetailsService;

public class FormBasedAuthenticationProvider implements AuthenticationProvider{
	private static final Log log= LogFactory.getLog(FormBasedAuthenticationProvider.class);
	private UserDetailsService userDetailsService;
	
	@Autowired
	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		
		if (authentication.getPrincipal() == null) {
			log.error("No userName found in principal of Authentication request.");
			throw new BadCredentialsException("No userName found in principal of Authentication request.");
		}
				
		try {
			UserDetails user = this.userDetailsService.getUser(String.valueOf(authentication.getPrincipal()), String.valueOf(authentication.getCredentials()));
			UsernamePasswordAuthenticationToken token= new UsernamePasswordAuthenticationToken(user, "N/A", user.getAuthorities());
			log.debug(String.format("User %s has been successfully authenticated", String.valueOf(authentication.getPrincipal())));
			return token;
		} catch (Exception e) {
			log.error(e);
			throw new AuthenticationCredentialsNotFoundException("Failed to authenticate user: "+authentication.getPrincipal()+". Reason: "+e.getMessage(),e);
		}
		
		
	}

	@Override
	public boolean supports(Class<? extends Object> authentication) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
	}

}
